package org.robot.scm.platform.registry.strategy;

import cn.hutool.core.io.FileUtil;
import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.DownloadFile;
import it.tdlight.jni.TdApi.Message;
import it.tdlight.jni.TdApi.MessageContent;
import it.tdlight.jni.TdApi.MessageDocument;
import java.io.File;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.platform.registry.TelegramRegistry;
import org.robot.scm.platform.server.telegram.ScmTelegram;
import org.robot.scm.utils.RandomUtil;

/**
 * 图文类型信息处理
 *
 * @Author : Awn create on 2025/4/21 17:00
 */
@Slf4j
public class DocumentMessageHandler extends AbstractMessageHandler {

    @Override
    protected Class clazz() {
        return MessageDocument.class;
    }

    @Override
    protected String doProcess(ScmTelegram scmTelegram, Message message, MessageContent messageContent) {
        MessageDocument document = (MessageDocument) messageContent;
        String fileName = document.document.fileName;

        // 如果是携带了文字的混合类型消息，额外处理下里面的文字
        String captain = document.caption.text;
        if (StringUtils.isNotBlank(captain)) {
            TextMessageHandler.handleForScm(captain, fileName);
        }
        try {
            // 文件大于1mb 或者 非sql文件 不下载
            if (!isSqlFile(fileName) || document.document.document.size > 1024 * 1024) {
                return "发来文件(" + (Math.round((float) document.document.document.size / 1024)) + "KB)";
            }

            TdApi.DownloadFile downloadFile = new TdApi.DownloadFile();
            downloadFile.fileId = document.document.document.id;
            downloadFile.priority = 1;
            downloadFile.synchronous = true;
            downloadAndSend(scmTelegram, downloadFile, message, fileName);
            return StringUtils.EMPTY;
        } catch (Exception e) {
            return "文件下载失败: " + fileName;
        }
    }

    private static void downloadAndSend(ScmTelegram scmTelegram, DownloadFile downloadFile, Message message, String fileName) {
        scmTelegram.getClient().send(downloadFile, file -> {
            String localPath = file.get().local.path;
            if (StringUtils.isBlank(localPath)) {
                sendMessage(scmTelegram, message, fileName);
                return;
            }
            File srcFile = new File(localPath);
            String sqlKey = RandomUtil.uuidNoLine();
            String fileIndex = Optional.ofNullable(FileUtil.extName(srcFile)).map(String::toLowerCase).orElse("");
            if (!isSqlFile(fileIndex)) {
                sendMessage(scmTelegram, message, fileName);
                return;
            }

            // 在源文件第一行添加文件名称并且空2行，方便核对文件名称
            List<String> lines = FileUtil.readLines(srcFile, "UTF-8");
            lines.add(0, "##### " + fileName + " #####");
            lines.add(1, StringUtils.EMPTY);
            lines.add(2, StringUtils.EMPTY);
            FileUtil.writeLines(lines, srcFile, "UTF-8");

            // 如果文件是txt或者sql或者无后缀的，则认为是sql语句
            TelegramRegistry.likeSqlKey.set(sqlKey);
            TelegramRegistry.likeSqlFile.set(fileName);

            // 所有txt、sql无后缀都认为是 sql语句
            String targetFileName = sqlKey.concat(".").concat("sql");
            File destFile = new File("assets/telegram/" + targetFileName);
            FileUtil.move(srcFile, destFile, true);
            sendMessage(scmTelegram, message, fileName);
        });
    }

}
